package com.example.denglu.Appframe;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.denglu.R;
import com.example.denglu.bean.Usesnewsnr;
import com.example.denglu.pages.News_pager.NewsActivity;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class DataFragment extends Fragment {
    private List<Usesnewsnr> usesnewsnrlistbean;
    private Banner newsbanner;
    private List<String> ImgUrllist;
    private RecyclerView newslist;
    private RecyclerView newsNr;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_data, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        setbanner();
        getnewslist();

    }

    private void setbanner() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                Request request = new Request.Builder()
                        .url("http://124.93.196.45:10001/prod-api/api/rotation/list?type=2")
                        .method("GET", null)
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String string = response.body().string();
                        try {
                            JSONObject stringjsonObject = new JSONObject(string);
                            int code = stringjsonObject.getInt("code");
                            if (code == 200) {

                                JSONArray rows = stringjsonObject.getJSONArray("rows");
                                ImgUrllist = new ArrayList<>();

                                for (int i = 0; i < rows.length(); i++) {
                                    JSONObject rowsJson = (JSONObject) rows.get(i);
                                    ImgUrllist.add("http://124.93.196.45:10001" + rowsJson.getString("advImg"));
                                }

                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        newsbanner.setAdapter(new BannerImageAdapter<String>(ImgUrllist) {
                                            @Override
                                            public void onBindView(BannerImageHolder bannerImageHolder, String s, int i, int i1) {

                                                Glide.with(bannerImageHolder.imageView).load(s).into(bannerImageHolder.imageView);
                                            }

                                        });
                                    }
                                });
                            } else {

                            }
                        } catch (JSONException e) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), "请求网络服务器失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
                try {
                    Response response = client.newCall(request).execute();
                } catch (IOException e) {


                }
            }
        }).start();

    }

    private void setnewslist(String id) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                RequestBody body = RequestBody.create(mediaType, "");
                Request request = new Request.Builder()
                        .url("http://124.93.196.45:10001/prod-api/press/press/list?type=" + id)
                        .method("GET", null)
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setTitle("系统提示：")
                                .setMessage("请求失败")
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Toast.makeText(getActivity(), "你点击了取消按钮~", Toast.LENGTH_SHORT).show();
                                    }
                                }).create().show();             //创建AlertDialog对象 //显示对话框
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String string = response.body().string();
                        try {
                            JSONObject jsonObject = new JSONObject(string);
                            int code = jsonObject.getInt("code");

                            if (code == 200) {
                                JSONArray rowsarr = jsonObject.getJSONArray("rows");
                                ArrayList<Usesnewsnr> usesnewsnrsarrbean = new ArrayList<>();

                                for (int i = 0; i < rowsarr.length(); i++) {
                                    JSONObject jsonObjectarr = (JSONObject) rowsarr.get(i);

                                    Usesnewsnr usesnewsNrarr = new Usesnewsnr();
                                    usesnewsNrarr.setURL("http://124.93.196.45:10001" + jsonObjectarr.getString("cover"));
                                    usesnewsNrarr.setId(jsonObjectarr.getString("id"));
                                    usesnewsNrarr.setContent(jsonObjectarr.getString("content"));
                                    usesnewsNrarr.setTitle(jsonObjectarr.getString("title"));
                                    usesnewsNrarr.setCreate(jsonObjectarr.getString("createTime"));
                                    usesnewsNrarr.setNewspl(jsonObjectarr.getString("commentNum"));
                                    usesnewsnrsarrbean.add(usesnewsNrarr);
                                }
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        newsNr.setLayoutManager(new LinearLayoutManager(getActivity()));
                                        newsNr.setAdapter(new RecyclerView.Adapter() {

                                            private int index = -1;

                                            class myho extends RecyclerView.ViewHolder {
                                                TextView textView, textViews, textViewContent, textViepl;
                                                ImageView imageView;
                                                LinearLayout linearLayout;

                                                public myho(@NonNull View itemView) {
                                                    super(itemView);
                                                    imageView = itemView.findViewById(R.id.newsNrimg);
                                                    textView = itemView.findViewById(R.id.newstitle);
                                                    textViews = itemView.findViewById(R.id.newsCreatetime);
                                                    textViepl = itemView.findViewById(R.id.newspl);
                                                    textViewContent = itemView.findViewById(R.id.NewsContent);
                                                    linearLayout = itemView.findViewById(R.id.newsclick);
                                                }
                                            }

                                            @NonNull
                                            @Override
                                            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                                                View view = getLayoutInflater().inflate(R.layout.layout_newsnr, null, false);
                                                myho myho = new myho(view);
                                                return myho;
                                            }

                                            @Override
                                            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                                                myho holder1 = (myho) holder;
                                                Glide.with(getActivity()).load(usesnewsnrsarrbean.get(position).getURL()).into(holder1.imageView);
                                                holder1.textView.setText(usesnewsnrsarrbean.get(position).getTitle());
                                                holder1.textViewContent.setText(Html.fromHtml(usesnewsnrsarrbean.get(position).getContent()));
                                                holder1.textViews.setText(usesnewsnrsarrbean.get(position).getCreate());
                                                holder1.textViepl.setText("评论数" + usesnewsnrsarrbean.get(position).getNewspl());

                                                if (index == position) {
                                                    Intent intent = new Intent(getActivity(), NewsActivity.class);
                                                    intent.putExtra("id", usesnewsnrsarrbean.get(index).getId());
                                                    startActivity(intent);
                                                }
                                                holder1.linearLayout.setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        index = position;
                                                        notifyDataSetChanged();
                                                    }
                                                });
                                            }

                                            @Override
                                            public int getItemCount() {
                                                return usesnewsnrsarrbean.size();
                                            }
                                        });
                                    }
                                });
                            } else {
                            }
                        } catch (JSONException e) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), "请求网络服务器失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    }
                });
                try {
                    Response response = client.newCall(request).execute();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        System.out.println("666");
    }

    private void getnewslist() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient().newBuilder()
                        .build();
                MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                Request request = new Request.Builder()
                        .url("http://124.93.196.45:10001/prod-api/press/category/list")
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .method("GET", null)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String string = response.body().string();
                        try {
                            JSONObject stringjsonObject = new JSONObject(string);
                            int code = stringjsonObject.getInt("code");
                            if (code == 200) {
                                JSONArray data = stringjsonObject.getJSONArray("data");

                                usesnewsnrlistbean = new ArrayList<>();

                                for (int i = 0; i < data.length(); i++) {
//                                    JSONObject rowsjsonObjectarr = (JSONObject) rows.get(i);
                                    JSONObject dataJson = (JSONObject) data.get(i);
                                    Usesnewsnr usesnewsnrbean = new Usesnewsnr();

                                    usesnewsnrbean.setId(dataJson.getString("id"));
                                    usesnewsnrbean.setTitle(dataJson.getString("name"));

                                    usesnewsnrlistbean.add(usesnewsnrbean);

                                }


                                getActivity().runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
                                        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                                        newslist.setLayoutManager(linearLayoutManager);
                                        newslist.setAdapter(new RecyclerView.Adapter() {

                                            private int index = 0;

                                            class myho extends RecyclerView.ViewHolder {
                                                TextView textView;

                                                public myho(@NonNull View itemView) {
                                                    super(itemView);
                                                    textView = itemView.findViewById(R.id.newstitle);
                                                }
                                            }

                                            @NonNull
                                            @Override
                                            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                                                View view = getLayoutInflater().inflate(R.layout.newstitle, null, false);
                                                myho myho = new myho(view);
                                                return myho;
                                            }

                                            @Override
                                            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                                                myho holder1 = (myho) holder;
                                                holder1.textView.setText(usesnewsnrlistbean.get(position).getTitle());

                                                if (index == position) {

                                                    holder1.textView.setTextColor(Color.parseColor("#0000ff"));
                                                    setnewslist(usesnewsnrlistbean.get(index).getId());

                                                } else {
                                                    holder1.textView.setTextColor(Color.parseColor("#303133"));

                                                }

                                                holder1.textView.setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        index = position;
                                                        notifyDataSetChanged();
                                                    }
                                                });
                                            }

                                            @Override
                                            public int getItemCount() {
                                                return usesnewsnrlistbean.size();
                                            }
                                        });
                                    }
                                });
                            } else {

                            }
                        } catch (JSONException e) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), "JOSN转换失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
                try {
                    Response response = client.newCall(request).execute();
                } catch (IOException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "请求网络服务器失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    private void initView(View view) {
        newsbanner = view.findViewById(R.id.newsbanner);
        newslist = view.findViewById(R.id.newslist);
        newsNr = view.findViewById(R.id.newsNr);
    }
}